import React, { useState, useCallback, useEffect } from 'react'
import { newsList } from '../../api'
import { List, Image, InfiniteScroll, PullToRefresh, Tabs, Toast } from 'antd-mobile'
import { sleep } from 'antd-mobile/es/utils/sleep'
import '../../assets/home.css'

const Index = () => {
  const types = [
    { "top": "推荐" },
    { "guonei": "国内" },
    { "guoji": "国际" },
    { "yule": "娱乐" },
    { "tiyu": "体育" },
    { "junshi": "军事" },
    { "keji": "科技" },
    { "caijing": "财经" },
    { "shishang": "时尚" },
    { "youxi": "游戏" },
    { "qiche": "汽车" },
    { "jiankang": "健康" }
  ]

  const [loading, setLoading] = useState(true)
  const [type, setType] = useState('top')
  const [news, setNews] = useState([])
  const [hasMore, setHasMore] = useState(true)

  const queryList = useCallback(async (getType = 'refresh') => {
    setLoading(true)
    const toast = Toast.show({
      icon: 'loading',
      content: '加载中…',
      duration: 0,
    })
    try {
      let res = await newsList(type)
      toast?.close()
      setLoading(false)
      if (res.error_code === 10012) {
        Toast.show({
          icon: 'fail',
          content: res.reason,
        })
      }
      if (getType !== 'refresh') {
        setNews([...news, ...res.result.data])
      } else {
        setNews(res.result.data)
      }
      console.log(res)
      setHasMore(res.result.data.length === 10)
    } catch (error) {
      setLoading(false)
      Toast.show({
        content: error,
        icon: 'fail',
      })
    }
  },
    [news, type]
  )

  const onTabsChange = (value) => {
    setType(value)
  }

  useEffect(() => {
    if (!loading) {
      console.log('&&&&&')
      queryList('refresh')
    }
  }, [type])
  console.log('???/')

  return (
    <>
      <Tabs onChange={onTabsChange}>
        {
          types.map(item => {
            const keys = Object.keys(item)
            return <Tabs.Tab title={item[keys[0]]} key={keys[0]} />
          })
        }
      </Tabs>
      <PullToRefresh
        onRefresh={async () => {
          await sleep(1000)
          queryList()
        }}
      >
        <List header='' mode="card">
          {
            news.map((item, index) => {
              return (
                <List.Item
                  key={item.uniquekey + index}
                  style={{
                    '--align-items': ''
                  }}
                  prefix={
                    <Image
                      src={item.thumbnail_pic_s}
                      style={{ borderRadius: 5 }}
                      fit="cover"
                      width={60}
                      height={60}
                    />
                  }
                  description={
                    <React.Fragment>
                      <span>{item.date}</span>
                      <span className='author'>{item.author_name}</span>
                    </React.Fragment>
                  }
                >
                  {item.title}
                </List.Item>
              )
            })
          }
        </List>
        <InfiniteScroll loadMore={() => queryList('more')} hasMore={hasMore} />
      </PullToRefresh>
    </>
  )
}

export default Index